import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'login.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'constants.dart';

int classid = -1;
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CreateClassWidget(),
    );
  }
}

class CreateClassWidget extends StatefulWidget {
  @override
  _CreateClassWidgetState createState() => _CreateClassWidgetState();
}

class _CreateClassWidgetState extends State<CreateClassWidget> {
  // 输入框控制器
  List<TextEditingController> TextFieldController =
      List.generate(7, (index) => TextEditingController());
  // 定义两个变量来存储下拉列表选择的值
  String? selectedWeekday = '周一';
  String? selectedTime = '8:30-10:00';

  @override
  void dispose() {
    // Clean up the controllers when the widget is disposed.
    for (int i = 0; i < TextFieldController.length; i++) {
      TextFieldController[i].dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final Width = size.width;
    final Height = size.height;
    return MaterialApp(
      home: Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text(
            '创建班级',
            style: TextStyle(color: Colors.grey[700]),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: Colors.black54,
            ),
            onPressed: () {
              // 返回按钮功能
              Navigator.pop(context);
            },
          ),
        ),
        body: SingleChildScrollView(
          padding: EdgeInsets.all(0.1 * Width),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                width: 0.88 * Width,
                height: 0.08 * Height,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(color: Colors.grey.shade200, blurRadius: 8)
                  ],
                ),
                child: TextField(
                  controller: TextFieldController[0],
                  maxLines: null,
                  maxLength: 40,
                  decoration: InputDecoration(
                    hintText: '输入班级名称, 如:软件工程3-4班',
                    contentPadding: EdgeInsets.all(10.0),
                    border: InputBorder.none,
                  ),
                ),
              ),
              SizedBox(height: 0.05 * Height),
              Container(
                width: 0.88 * Width,
                height: 0.5 * Height,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(color: Colors.grey.shade200, blurRadius: 8)
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(6.0),
                      child: Text("开始日期"),
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: TextField(
                              controller: TextFieldController[1],
                              keyboardType: TextInputType.number, // 添加数字键盘
                              decoration: InputDecoration(
                                hintText: '年',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: TextField(
                              controller: TextFieldController[2],
                              keyboardType: TextInputType.number, // 添加数字键盘
                              decoration: InputDecoration(
                                hintText: '月',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: TextField(
                              controller: TextFieldController[3],
                              keyboardType: TextInputType.number, // 添加数字键盘
                              decoration: InputDecoration(
                                hintText: '日',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.all(6.0),
                      child: Text("结束日期"),
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: TextField(
                              controller: TextFieldController[4],
                              keyboardType: TextInputType.number, // 添加数字键盘
                              decoration: InputDecoration(
                                hintText: '年',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: TextField(
                              controller: TextFieldController[5],
                              keyboardType: TextInputType.number, // 添加数字键盘
                              decoration: InputDecoration(
                                hintText: '月',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: TextField(
                              controller: TextFieldController[6],
                              keyboardType: TextInputType.number, // 添加数字键盘
                              decoration: InputDecoration(
                                hintText: '日',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.all(6.0),
                      child: Text("上课时间"),
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: DropdownButton<String>(
                              value: selectedWeekday,
                              onChanged: (String? newValue) {
                                setState(() {
                                  selectedWeekday = newValue;
                                });
                              },
                              items: <String>[
                                '周一',
                                '周二',
                                '周三',
                                '周四',
                                '周五',
                                '周六',
                                '周日'
                              ].map((String value) {
                                return DropdownMenuItem<String>(
                                  value: value,
                                  child: Text(value),
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: DropdownButton<String>(
                              value: selectedTime,
                              onChanged: (String? newValue) {
                                setState(() {
                                  selectedTime = newValue;
                                });
                              },
                              items: <String>[
                                '8:30-10:00',
                                '10:20-11:50',
                                '14:00-15:30',
                                '15:50-17:20',
                                '18:50-20:10',
                                '20:20-21:40'
                              ].map((String value) {
                                return DropdownMenuItem<String>(
                                  value: value,
                                  child: Text(value),
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 0.04 * Height),
              Row(
                children: [
                  Expanded(
                    child: MaterialButton(
                        color: Colors.white,
                        shape: const RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(8),
                          ),
                        ),
                        minWidth: 0.4 * Width, // 修改按钮的最小宽度
                        height: 0.07 * Height,
                        onPressed: () {
                          for (int i = 0; i < TextFieldController.length; i++) {
                            TextFieldController[i].clear();
                          }
                        },
                        child: const Text(
                          "清空",
                          style: TextStyle(fontSize: 14, color: Colors.black87),
                        )),
                  ),
                  SizedBox(width: 0.08 * Width),
                  Expanded(
                    child: MaterialButton(
                        color: Color.fromARGB(255, 179, 202, 193),
                        shape: const RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(8),
                          ),
                        ),
                        minWidth: 0.4 * Width, // 修改按钮的最小宽度
                        height: 0.07 * Height,
                        onPressed: () {
                          String className = TextFieldController[0].text;
                          // 格式：课程开始日期||每周几上课，上课时间段|每周几上课，上课时间段|.....||课程结束日期
                          // 示例：|2023.9.4|周五14:00-15:30|2024.1.15|
                          String classTime =
                              '|${TextFieldController[1].text}.${TextFieldController[2].text}.${TextFieldController[3].text}|${selectedWeekday}${selectedTime}|${TextFieldController[4].text}.${TextFieldController[5].text}.${TextFieldController[6].text}|';
                          createClass(className, classTime);
                          // showDialog(
                          //     context: context,
                          //     barrierDismissible: true,
                          //     builder: (BuildContext context) {
                          //       return newClassCode();
                          //     });
                        },
                        child: const Text(
                          "确认",
                          style: TextStyle(fontSize: 16, color: Colors.white),
                        )),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> createClass(String name, String time) async {
    String jwtToken = await retrieveJwtToken('access_token');
    if (jwtToken == '' && !isJwtExpired(jwtToken)) {
      print('No JWT token found or expire.');
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Login()),
      );
      return;
    }
    String serverUrl = AppConstants.serverUrl;

    try {
      var response = await http.post(Uri.parse('$serverUrl/v1/createClass'),
          headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer $jwtToken"
          },
          body: jsonEncode({
            "class_name": name,
            "class_time": time,
          }));

      if (response.statusCode == 200) {
        // Handle the response
        print("create Class successful");
        final Map<String, dynamic> responseData = jsonDecode(response.body);
        if (responseData.containsKey('class_id')) {
          setState(() {
            classid = responseData['class_id'];
          });
        }
        showDialog(
            context: context,
            barrierDismissible: true,
            builder: (BuildContext context) {
              return newClassCode();
            });
      } else {
        // Handle error
        print("Failed to create Class: ${response.body}");
      }
    } catch (e) {
      // Handle exception
      print("Error occurred: $e");
    }
  }
}

class newClassCode extends StatelessWidget {
  String generateRandomQRCode() {
    final String randomData = DateTime.now().toIso8601String();
    return randomData;
  }

  @override
  Widget build(BuildContext context) {
    final String qrData = generateRandomQRCode();
    final size = MediaQuery.of(context).size;
    final Width = size.width;
    final Height = size.height;
    return Dialog(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              IconButton(
                icon: Icon(Icons.share),
                onPressed: () {
                  // Add your code to handle sharing here
                },
              ),
            ],
          ),
          QrImageView(
            data: classid.toString(),
            size: 150.0,
          ),
          SizedBox(height: 0.05 * Height),
          Text(
            "班级邀请码: $classid", // TODO: 换成随机邀请码
            style: TextStyle(fontSize: 14, color: Colors.black87),
          ),
          SizedBox(height: 0.05 * Height),
          MaterialButton(
              color: Colors.blue,
              shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(40),
                ),
              ),
              minWidth: 0.4 * Width,
              height: 0.08 * Height,
              onPressed: () {},
              child: const Text(
                "保存到本地",
                style: TextStyle(fontSize: 16, color: Colors.white),
              )),
        ],
      ),
    );
  }
}
